# -*- coding: utf-8 -*-

from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _

from djmarkitup.models import DjMarkItUpBase

# Create your models here.


class Tag(models.Model):
    name = models.CharField(_(u'Name'), max_length=30, unique=True)
    description = models.TextField(_(u'Description'), blank=True)

    def __unicode__(self):
        return self.name


class Board(models.Model):
    subject = models.CharField(_(u'Subject'), max_length=60, unique=True)
    slug = models.SlugField(max_length=60)
    description = models.TextField(_(u'Description'))
    last_post = models.DateTimeField(_(u'Last Post'), blank=True, null=True)
    internal = models.BooleanField(_(u'Internal'), default=False)
    guest_post = models.BooleanField(_(u'Guest Post'), default=False,
        help_text=_(u'This field is only used if settings.GUEST_POST is true.')
    )
    moderators = models.ManyToManyField(User, verbose_name=_(u'Moderators'))
    display_position = models.IntegerField(_(u'Display Position'), blank=True)

    def __unicode__(self):
        return self.subject

    def save(self, *args, **kw):
        if not self.display_position:
            self.display_position = Board.objects.all().count() + 1
        super(Board, self).save(*args, **kw)

    def get_topics(self):
        return self.posts.filter(topic__isnull=True)

    def topics_count(self):
        return self.get_topics().count()


class Post(DjMarkItUpBase):
    subject = models.CharField(_(u'Subject'), max_length=100)
    slug = models.SlugField(max_length=100, blank=True)
    editors = models.ManyToManyField(User, verbose_name=_(u'Editors'),
        related_name='edited_posts', through='PostHistory')
    board = models.ForeignKey(Board, verbose_name=_(u'Board'),
        related_name='posts')
    tags = models.ManyToManyField(Tag, verbose_name=_(u'Tag'),
        related_name='posts', blank=True, null=True)
    topic = models.ForeignKey('self', verbose_name=_('Topic'),
        related_name='replies', blank=True, null=True)
    sticky = models.BooleanField(_(u'Sticky'), default=False)
    closed = models.BooleanField(_(u'Closed'), default=False)
    read_count = models.IntegerField(default=0, editable=False)

    @property
    def is_topic(self):
        return self.topic is None

    @property
    def author(self):
        u = self.editors.all().order_by('editors__stamp')[0]
        return u


class PostHistory(models.Model):
    user = models.ForeignKey(User)
    post = models.ForeignKey(Post)
    stamp = models.DateTimeField(auto_now_add=True)
    reason = models.CharField(max_length=100, blank=True)
